package com.example.demo.repository;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import com.example.demo.model.Fund;

public interface FundRepository extends JpaRepository<Fund, Long>, JpaSpecificationExecutor<Fund> {

	@SuppressWarnings("serial")
	public default Page<Fund> pageCriteria(Fund fund, Pageable pageable) {

		Page<Fund> page = this.findAll(new Specification<Fund>() {
			@Override
			public Predicate toPredicate(Root<Fund> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				if (fund.getuID() != null) {
					list.add(cb.equal(root.<Long> get("uID"), fund.getuID()));
				}
				if (StringUtils.isNotEmpty(fund.getFundNo())) {
					list.add(cb.like(root.<String> get("fundNo"), "%" + fund.getFundNo() + "%"));
				}
				if (fund.getFundType()!=null) {
					list.add(cb.equal(root.<Integer> get("fundType"), fund.getFundType()));
				}
				cb.desc(root.<Long> get("updateTime"));

				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}

		}, pageable);
		return page;
	}

	@Query("from Fund f where f.fundNo = ?1")
	public Fund getByFundNo(String fundNo);
	
	@Query("from Fund f where f.fID = ?1")
	public Fund getByID(long fID);

}
